package com.wangwenjun.concurrency.chapter17;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 *
 * 1.LockSupport.unpark(thread);
 * 2.LockSupport.park();
 * thread线程不会阻塞
 *
 */
public class TaoBaoTest9 {




    private static int flag = 1;

    public static void main(String[] args) throws InterruptedException {


        ReentrantLock lock = new ReentrantLock();
        Condition condition1 = lock.newCondition();
        Condition condition2 = lock.newCondition();
        Condition condition3 = lock.newCondition();

        new Thread(() -> {
            for (int i = 0; i < 3; i++) {
                lock.lock();
                while (flag != 3){
                    try {
                        condition3.await();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }

                }
                try{
                    System.out.println("c");
                    flag = 1;
                    condition1.signal();
                }finally {
                    lock.unlock();
                }
            }
        }, "t3").start();


        new Thread(() -> {
            for (int i = 0; i < 3; i++) {
                lock.lock();
                while (flag != 2){
                    try {
                        condition2.await();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }

                }
                try{
                    System.out.println("b");
                    flag = 3;
                    condition3.signal();
                }finally {
                    lock.unlock();
                }
            }
        }, "t2").start();

        TimeUnit.SECONDS.sleep(1);

        new Thread(() -> {
            for (int i = 0; i < 3; i++) {
                lock.lock();
                while (flag != 1){
                    try {
                        condition1.await();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }

                }
                try{
                    System.out.println("a");
                    flag = 2;
                    condition2.signal();
                }finally {
                    lock.unlock();
                }
            }
        }, "t1").start();




    }









}
